package com.dsbj.mp.icardservice.config.intercept;

import com.alibaba.fastjson.JSONObject;
import com.dsbj.common.msg.ResponseMessage;
import com.dsbj.mp.icardservice.model.MpUser;
import com.dsbj.mp.icardservice.utils.Constants;
import com.dsbj.mp.icardservice.utils.jwt.IJWTInfo;
import com.dsbj.mp.icardservice.utils.jwt.UserAuthUtil;
import com.dsbj.mp.icardservice.utils.jwt.exception.JwtIllegalArgumentException;
import com.dsbj.mp.icardservice.utils.jwt.exception.JwtSignatureException;
import com.dsbj.mp.icardservice.utils.jwt.exception.JwtTokenExpiredException;
import com.dsbj.mp.icardservice.utils.strprocess.StrUtil;
import com.dsbj.mp.icardservice.webserviceclient.dsbjpmc.WxUser;
import io.jsonwebtoken.MalformedJwtException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户token拦截器。
 * @author cjw 2019-11-26
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private UserAuthUtil userAuthUtil;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//logger.info("执行了TokenInterceptor.preHandle()..");

		String token = request.getHeader(Constants.USER_TOKEN);
		if (StringUtils.isEmpty(token)) {
			String errMsg="[ip="+request.getRemoteAddr()+"][url="+request.getRequestURI()+"] 未传入有效的Token!";
			logger.error(errMsg);
			renderResponse(response, ResponseMessage.error(50005, "未传入有效的Token!"));
			return false;
		}
		
		/**
		 * 若token不为空
		 */
		MpUser mpUser = userAuthUtil.getUserInfoFromToken(token);
		if(mpUser==null){
			renderResponse(response, ResponseMessage.error(50001, "用户Token已过期!"));
			return false;
		}
		//兼容之前程序。
		request.setAttribute("wxUser",mpUser);
		request.setAttribute("mpUser",mpUser);
		return true;
	}
	
	/**
	 * 以JSON格式输出
	 *
	 * @param response
	 */
	public static void renderResponse(HttpServletResponse response, Object responseObject) {
		//将实体对象转换为JSON Object转换
		String jsonStr = JSONObject.toJSONString(responseObject);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(jsonStr);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// super.postHandle(request, response, handler, modelAndView);
	}


}
